﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using SmallERP.COM;
using SmallERP.MODEL.FoundationModel;

namespace SmallERP.WastePaperManage
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool isAppRunning = false;
            System.Threading.Mutex mutex = new System.Threading.Mutex(
                false,
                System.Diagnostics.Process.GetCurrentProcess().ProcessName,
                out isAppRunning);

            if (!isAppRunning)
            {
                return;
            }
            else
            {
                if (DealResult())
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    System.Threading.Timer t = new System.Threading.Timer(t_Tick, null, 60000, 100);
                    Application.Run(new FrmMain());
                }
            }
        }
        #region 公共的
        private static StartUPUtil _upBLL;
        private static bool isDoing = false;
        static void t_Tick(object sender)
        {
            if (!isDoing)
            {
                isDoing = true;
                if (_upBLL == null)
                {
                    _upBLL = new StartUPUtil();
                }
                //StartUPUtil upBLL = new StartUPUtil();
                ServerInfo serverInfo = new ServerInfo();
                string errMsg = string.Empty;
                int result = _upBLL.GetServerInfo(out serverInfo, out errMsg);
                if (result != 0)
                {
                    MessageBox.Show("与服务器失去连接，程序将立即重启，请检查与服务器的连接！");
                    Environment.Exit(0);
                }
                isDoing = false;
            }
        }

        private static bool DealResult()
        {
            if (_upBLL == null)
            {
                _upBLL = new StartUPUtil();
            }
            //StartUPUtil upBLL = new StartUPUtil();
            ServerInfo serverInfo = new ServerInfo();
            string errMsg = string.Empty;
            int result = _upBLL.GetServerInfo(out serverInfo, out errMsg);
            if (result != 0)//有问题
            {
                MessageBox.Show(errMsg);

                if (result == -6)
                {
                    Application.ApplicationExit += new EventHandler(Restart);
                }

                Application.Exit();
                return false;
            }

            //Properties.Settings.Default.ServerIP = serverInfo.ServerIP;
            //Properties.Settings.Default.ServerPort = serverInfo.ServerTCPPort;
            return true;
        }

        private static void Restart(object sender, EventArgs e)
        {
            Process.Start(Application.ExecutablePath);
        }
        #endregion
    }
}
